import os

from flask import Blueprint, render_template, request, session, jsonify, redirect, url_for, current_app


from fun import imageCode, allowed_file, generate_random_filename, model_to_dict, verify_password
from models import DAdmin,DCategory,DNew
import datetime
from exts import db
admin_index = Blueprint('index',__name__,url_prefix='/index')

#后台框架页
@admin_index.route('/index')
def index():
     return render_template('admin/index/index.html')

#后台主页
@admin_index.route('/main')
def main():
    cate=DCategory.query.count()
    new = DNew.query.count()
    admin =DAdmin.query.count()
    return render_template('admin/index/main.html',data={'cate':cate,'new':new,'admin':admin})

#登陆
@admin_index.route('/login',methods=['GET','POST'])
def login():
    if request.method=='POST':
        post=request.form.to_dict()

        if post['vercode'].lower()==session.get('vercode').lower():
            info=DAdmin.query.filter(DAdmin.name == post['username']).filter(DAdmin.status == 0).first()
            if info==None:
                return jsonify({'code': 500, 'msg': "帐号或密码错误!"})
            else:
                if(verify_password(info.pwd,post['password'])):
                    session['admin_id']=info.id
                    session['admin_name'] = info.name
                    ip = request.remote_addr
                    DAdmin.query.filter(DAdmin.id == info.id).update({'ip': ip,'update':datetime.datetime.now()})
                    db.session.commit()
                    return jsonify({'code': 200, 'msg': "登陆成功!"})
                else:
                    return jsonify({'code': 500, 'msg': "帐号或密码错误!"})
        else:
            return jsonify({'code':500,'msg':"验证码错误!"})
    else:
        return render_template('admin/index/login.html')

#退出登陆
@admin_index.route('/logout')
def logout():
    # 清空所有的session条目
    session.clear()
    # 删除session的cookie
    session.pop('admin_id', None)
    session.pop('admin_name', None)

    return redirect(url_for('admin.index.login'))

#验证码
@admin_index.route('/captcha')
def captcha():
    return imageCode().getImgCode()

#清空缓存
@admin_index.route('/clear')
def clear():
    return jsonify({'code': 200, 'msg': "暂时没涉及到!"})

#上传文件
@admin_index.route('/upload',methods=['POST'])
def upload():
    if 'file' not in request.files:
        print('无文件部分')
        return ''

    file = request.files['file']
    if file.filename == '':
        print('没有选择文件')
        return ''

    if file:
        app = current_app._get_current_object()
        if file and allowed_file(file.filename,app.config['ALLOWED_EXTENSIONS']):
            #filename = secure_filename(file.filename)
            filename=generate_random_filename(6)+os.path.splitext(file.filename)[1]
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            return jsonify({'code': 200, 'url': '/upload/'+filename})
        else:
            print("文件类型不正确")
            return ''